package cn.rxyb.core.io.file;

import cn.rxyb.core.io.IoUtil;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author YJH
 * @version 1.0
 * @description 文件读取
 * @date 2020/6/28 14:18
 */
public class FileReader extends FileWrapper {

    public FileReader(File file) {
        super(file);
    }

    public FileReader(File file, Charset charset) {
        super(file, charset);
    }

    public FileReader(String filePath) {
        super(filePath);
    }

    public FileReader(String filePath, Charset charset) {
        super(filePath, charset);
    }

    /**
     * 读取文件所有数据<br>
     * 文件的长度不能超过 {@link Integer#MAX_VALUE}
     *
     * @return 字节码
     * @throws IOException IO异常
     */
    public byte[] readBytes() {
        long len = file.length();
        if (len >= Integer.MAX_VALUE) {
            throw new RuntimeException("文件过大无法读取");
        }

        byte[] bytes = new byte[(int) len];
        FileInputStream in = null;
        int readLength;
        try {
            in = new FileInputStream(file);
            readLength = in.read(bytes);
            if (readLength < len) {
                throw new IOException();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(in);
        }
        return bytes;
    }


    /**
     * 读取文件内容
     *
     * @return 读取文件内容
     * @throws IOException 异常
     */
    public String readString() throws IOException {
        return new String(readBytes());
    }

    /**
     * 读取文件的每一行
     *
     * @param collection 集合类型
     * @param <T>集合类型
     * @return 返回集合
     * @throws IOException
     */
    public <T extends Collection<String>> T readLines(T collection) {
        BufferedReader reader = null;
        try {
            InputStreamReader inputStream = null;
            if (null == charset) {
                inputStream = new InputStreamReader(IoUtil.getInputStream(file));
            } else {
                inputStream = new InputStreamReader(IoUtil.getInputStream(file), this.charset);
            }
            reader = new BufferedReader(inputStream);
            String line;
            while (true) {
                line = reader.readLine();
                if (line == null) {
                    break;
                }
                collection.add(line);
            }
            return collection;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(reader);
        }
        return null;
    }

    /**
     * 获取文件共有多少行
     *
     * @return
     * @throws IOException IO 异常
     */
    public long readLength() {
        return this.readLines(new ArrayList<>()).size();
    }
}
